package com.sunxd.limit.core;

import com.sunxd.limit.beans.params.AbsRequest;
import com.sunxd.limit.beans.params.Context;
import com.sunxd.limit.beans.params.Limit;
import com.sunxd.limit.core.support.LimitHandlerSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author sun.xd
 * @description: description
 * @date 2024/10/23 19:52
 */
@Slf4j
public class LimitHandlerUtil {

    public static Boolean judge(Context context){
        AbstractLimitHandler handler = LimitHandlerSupport.getHandler(context.getLimitGroup());
        if(Objects.isNull(handler)){
            log.error("not find limitGroup :  limitGroup : {}",context.getLimitGroup());
            return Boolean.FALSE;
        }
        return handler.doJudge(context);

    }

    public static Boolean judge(String limitAnnotationGroup, List<Limit> limits, AbsRequest request){
        if(CollectionUtils.isEmpty(limits) || StringUtils.isEmpty(limitAnnotationGroup) ){
            log.info("not set limit List. return");
            return Boolean.TRUE;
        }
        return judge(Context.builder()
                .limitGroup(limitAnnotationGroup)
                .limitMap(limits.stream().collect(Collectors.toMap(Limit::getKey, Function.identity(),(o1, o2) -> o1)))
                .request(request).build());

    }



}
